package com.thti.mecool.client.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.base.HandlerConstant;
import com.thti.mecool.client.model.biz.PlanBizImpl;
import com.thti.mecool.client.model.biz.ProjectBizImpl;
import com.thti.mecool.client.model.biz.TaskBizImpl;
import com.thti.mecool.client.model.po.PlanClient;
import com.thti.mecool.client.model.po.Project;
import com.thti.mecool.client.model.po.Task;
import com.thti.mecool.client.util.RegexPattern;
import com.thti.mecool.client.util.StringUtil;
import com.thti.mecool.client.util.TimeUtil;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.Toolbar;

public class AddPlanActivity extends BaseActivity {
	private Button date, startTime, endTime, sureBtn, cancelBtn;
	private LinearLayout selectProjectLinearLayout, selectTaskLinearLayout,
			selectStoreLinearLayout;
	private TextView projectContent, taskContent, storeContent;
	private EditText projectTitle; 
	private ProjectBizImpl projectBizImpl;
	private TaskBizImpl taskBizImpl;
	private PlanBizImpl planBizImpl;
	private PlanClient plan;
	private int planid;
	private String curProjectId, curProjectStoreId, curTaskId;
	private String ProjectName;
	private boolean ContinueAdd = false;
	private boolean startTimeChoice = false;
	private boolean isMyplan = false;
	String time;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.noTitle();
		setContentView(R.layout.mecool_make_plan_set_time);
		initToolbar();
		this.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		Cache.add(this);
		init();
		service();
	}

	private void init() {
		date = (Button) findViewById(R.id.mecool_make_plan_set_time_Date);
		startTime = (Button) findViewById(R.id.mecool_make_plan_set_time_starttime);
		endTime = (Button) findViewById(R.id.mecool_make_plan_set_time_endtime);
		sureBtn = (Button) findViewById(R.id.mecool_make_plan_set_time_sure);
		cancelBtn = (Button) findViewById(R.id.mecool_make_plan_set_time_cancel);
		selectProjectLinearLayout = (LinearLayout) findViewById(R.id.mecool_make_plan_set_time_select_project);
		selectTaskLinearLayout = (LinearLayout) findViewById(R.id.mecool_make_plan_set_time_select_task);
		selectStoreLinearLayout = (LinearLayout) findViewById(R.id.mecool_make_plan_set_time_select_store);
		projectContent = (TextView) findViewById(R.id.mecool_make_plan_set_time_select_project_content);
		taskContent = (TextView) findViewById(R.id.mecool_make_plan_set_time_select_task_content);
		storeContent = (TextView) findViewById(R.id.mecool_make_plan_set_time_select_store_content);
		projectTitle = (EditText) findViewById(R.id.mecool_make_plan_set_time_project_title);
		StringUtil.lengthFilter(this, projectTitle, 50, null);
		projectBizImpl = new ProjectBizImpl(this);
		taskBizImpl = new TaskBizImpl(this);
		planBizImpl = new PlanBizImpl(this);
		Intent i = getIntent();
		ContinueAdd = i.getBooleanExtra("ContinueAdd", false);
		planid = i.getIntExtra("curPlanId", -1);
		System.out.println("planid    :   "+planid);
		curTaskId = i.getStringExtra("curTaskId");
		System.out.println("curTaskId     :    " +curTaskId);
		isMyplan = i.getBooleanExtra("ismyplan", false);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date curDate = new Date(System.currentTimeMillis());
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(curDate);
		calendar.add(Calendar.DATE, 1);
		time = sdf.format(calendar.getTime());
		date.setText(time);

	}

	public void initToolbar() {
		Toolbar toolbar = new Toolbar(this);
		toolbar.setToolbarCentreText("添加任务");
		Toolbar.left_btn.setOnClickListener(leftbuttonListener);
		Toolbar.left_btn.setImageResource(R.drawable.mecool_go_back);
		Toolbar.hideRightButton();
	}

	private void service() {
		date.setOnClickListener(new ClickEvent());
		startTime.setOnClickListener(new ClickEvent());
		endTime.setOnClickListener(new ClickEvent());
		sureBtn.setOnClickListener(new ClickEvent());
		cancelBtn.setOnClickListener(new ClickEvent());
		selectProjectLinearLayout.setOnClickListener(new ClickEvent());
		selectTaskLinearLayout.setOnClickListener(new ClickEvent());
		selectStoreLinearLayout.setOnClickListener(new ClickEvent());

		if (ContinueAdd & planid != -1) {
			if (isMyplan) {
				plan = planBizImpl.findByPlanId(2, planid,
						String.valueOf(getCurrentUser().getId()));
			} else {
				plan = planBizImpl.findByPlanId(0, planid,
						String.valueOf(getCurrentUser().getId()));
			}
			projectTitle.setText(plan.getPlanName());
			projectTitle.setEnabled(false);
			time = plan.getPlanTime();
			date.setText(time);
			date.setEnabled(false);
		}
	}

	private OnClickListener leftbuttonListener = new ImageButton.OnClickListener() {
		@Override
		public void onClick(View v) {
			finish();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		// 项目
		if (requestCode == 10) {
			if (resultCode == RESULT_OK) {
				Bundle b = data.getExtras();
				ProjectName = b.getString("ProjectName");
				curProjectId = b.getString("ProjectId");
				projectContent.setText(ProjectName);
			}
		}

		// 任务
		if (requestCode == 11) {
			if (resultCode == RESULT_OK) {
				Bundle b = data.getExtras();
				taskContent.setText(b.getString("TaskName"));
				curTaskId = b.getString("TaskId");
			}
		}

		// 计划
		if (requestCode == 12) {
			if (resultCode == RESULT_OK) {
				Bundle b = data.getExtras();
				storeContent.setText(b.getString("ProjectStoreName"));
				curProjectStoreId = b.getString("ProjectStoreId");
			}
		}
	}

	class ClickEvent implements OnClickListener {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			switch (v.getId()) {
			case R.id.mecool_make_plan_set_time_Date:
				new DatePickerDialog(AddPlanActivity.this,
						new OnDateSetListener() {
							@Override
							public void onDateSet(DatePicker view, int year,
									int monthOfYear, int dayOfMonth) {
								if (TimeUtil.judgeCurDate(1, new Date(
										year - 1900, monthOfYear, dayOfMonth))) {
									Util.sendToast(AddPlanActivity.this,
											"日期必须大于今天");
								} else {
									time = TimeUtil.dateToYYYYMM(new Date(
											year - 1900, monthOfYear,
											dayOfMonth));
									date.setText(time);
								}
							};
						}, Calendar.getInstance().get(Calendar.YEAR), Calendar
								.getInstance().get(Calendar.MONTH), Calendar
								.getInstance().get(Calendar.DAY_OF_MONTH))
						.show();

				break;
			case R.id.mecool_make_plan_set_time_select_project:
				storeContent.setText("");
				intent.setClass(AddPlanActivity.this,
						MakePlanSelectProjectActivity.class);
				startActivityForResult(intent, 10);
				break;
			case R.id.mecool_make_plan_set_time_select_task:
				if (StringUtil.isBlank(projectContent.getText().toString())) {
					Util.sendToast(AddPlanActivity.this, "请先选择项目");
				} else {
					intent.putExtra("projectId", curProjectId);
					intent.setClass(AddPlanActivity.this,
							MakePlanSelectTaskActivity.class);
					startActivityForResult(intent, 11);
				}
				break;
			case R.id.mecool_make_plan_set_time_select_store:
				if (StringUtil.isBlank(projectContent.getText().toString())) {
					Util.sendToast(AddPlanActivity.this, "请先选择项目");
				} else {
					intent.setClass(AddPlanActivity.this,
							MakePlanSelectTerminalActivity.class);
					intent.putExtra("curProjectId", curProjectId);
					startActivityForResult(intent, 12);
				}
				break;
			case R.id.mecool_make_plan_set_time_starttime:
				new TimePickerDialog(AddPlanActivity.this,
						new OnTimeSetListener() {
							@Override
							public void onTimeSet(TimePicker view,
									int hourOfDay, int minute) {
								startTime.setText(TimeUtil.DateConvert(
										hourOfDay + ":" + minute, 3));
								startTimeChoice = true;
							};
						}, Calendar.getInstance().get(Calendar.HOUR_OF_DAY),
						Calendar.getInstance().get(Calendar.MINUTE), true)
						.show();
				break;

			case R.id.mecool_make_plan_set_time_endtime:
				new TimePickerDialog(AddPlanActivity.this,
						new OnTimeSetListener() {

							@Override
							public void onTimeSet(TimePicker view,
									int hourOfDay, int minute) {
								view.setIs24HourView(true);
								if (startTimeChoice) {
									if (TimeUtil.judgeCurTime(1, hourOfDay
											+ ":" + minute, startTime.getText()
											.toString())) {
										endTime.setText(TimeUtil.DateConvert(
												hourOfDay + ":" + minute, 3));
									} else {
										Util.sendToast(AddPlanActivity.this,
												"结束时间必须于开始时间");
									}
								} else {
									Util.sendToast(AddPlanActivity.this,
											"请先选择开始时间");
								}
							};
						}, Calendar.getInstance().get(Calendar.HOUR_OF_DAY),
						Calendar.getInstance().get(Calendar.MINUTE), true)
						.show();
				break;

			case R.id.mecool_make_plan_set_time_sure:
				if (judge())
					registerPlan();
				break;
			case R.id.mecool_make_plan_set_time_cancel:
				if (judge())
					new AlertDialog.Builder(AddPlanActivity.this)
							.setTitle("提示").setMessage("您填写的计划还没有保存，确认要退出吗？")
							.setNegativeButton("取消", onClickListener)
							.setPositiveButton("确认", onClickListener).create()
							.show();
				else
					finish();
				break;
			default:
				finish();
				break;
			}
		}
	}

	android.content.DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case -1:
				finish();
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (getDataFlag(HandlerConstant.PlanCommand))
			;
		removeDataFlag(HandlerConstant.PlanCommand);
	}

	public boolean judge() {
		if (StringUtil.isBlank(projectTitle.getText().toString())) {
			projectTitle.setError("计划名称不能为空！");
			return false;
		}
		if (RegexPattern.isChars(projectTitle.getText().toString())) {
			projectTitle.setError("请误输入非法字符");
			return false;
		}
		if (StringUtil.isBlank(projectContent.getText().toString())) {
			Util.sendToast(this, "请选择项目！");
			return false;
		}
		if (StringUtil.isBlank(taskContent.getText().toString())) {
			Util.sendToast(this, "请选择任务！");
			return false;
		}
		if (StringUtil.isBlank(storeContent.getText().toString())) {
			Util.sendToast(this, "请选择终端！");
			return false;
		}
		if (!TimeUtil.judgeCurDate(time)) {
			Util.sendToast(AddPlanActivity.this, "日期必须大于今天");
			return false;
		}
		if (StringUtil.isBlank(startTime.getText().toString())) {
			Util.sendToast(this, "请选择开始时间");
			return false;
		}
		if (StringUtil.isBlank(endTime.getText().toString())) {
			Util.sendToast(this, "请选择结束时间");
			return false;
		}
		if (!TimeUtil.judgeCurTime(1, endTime.getText().toString(), startTime
				.getText().toString())) {
			Util.sendToast(this, "开始时间必须小于结束时间");
			return false;
		}
		if(planBizImpl.planIsexistDate(date.getText().toString())){
			Util.sendToast(this, "当天已有计划存在");
			return false;
		}
		return true;
	}

	public void savetask(String local) {
		Task task = new Task(curTaskId, taskContent.getText().toString(),
				curProjectId, TimeUtil.DateConvert(startTime.getText()
						.toString(), 2), TimeUtil.DateConvert(endTime.getText()
						.toString(), 2), curProjectStoreId, storeContent
						.getText().toString(), String.valueOf(getCurrentUser()
						.getId()), String.valueOf(planid), local);
		taskBizImpl.save(task);
	}

	public void saveProject(int isType) {
		String userId = String.valueOf(getCurrentUser().getId());
		if (!ContinueAdd & planid == -1) {
			planid = planBizImpl.findPlanId();
			System.out.println("planId    :    "+planid);
			PlanClient plan = new PlanClient(String.valueOf(planid),
					projectTitle.getText().toString(), userId, 0, isType, time,
					new Date());
			planBizImpl.save(plan);
		}
		Project project = new Project(curProjectId, ProjectName,
				String.valueOf(planid), isType, String.valueOf(getCurrentUser()
						.getId()), new Date());
		if (!projectBizImpl.findProjectId(curProjectId, String.valueOf(planid)))
			projectBizImpl.save(project);
	}

	public void registerPlan() {
		Util.sendToast(AddPlanActivity.this, "成功"); // userId,projectId,projectName,planId,isType
		if (isMyplan) {
			saveProject(2);
			savetask("local");
			} else {
			saveProject(0);
			savetask("");
			Intent intent1 = new Intent();
			intent1.putExtra("curPlanid", String.valueOf(planid));
			intent1.putExtra("curTaskId", curTaskId);
			intent1.setClass(AddPlanActivity.this, DraftPlanTaskActivity.class);
			startActivity(intent1);
			finish();
		}
	
	}

}
